<template>
    <el-card class="box-card">
        <!-- 卡片顶部添加品牌按钮 -->
        <el-button type="primary" icon="Plus" @click="addTradeMark" v-has="'btn.Trademark.add'">添加品牌</el-button>
        <!-- 表格组件：用于展示已有的平台数据 -->
        <el-table style="margin: 10px 0;" border :data="trademarkArr">
            <el-table-column label="序号" width="80" align="center" type="index" />
            <!-- <el-table-column label="品牌名称" align="center">
                <template #default="scope">
                    <span>{{ scope.row.tmName }}</span>
                </template>
</el-table-column> -->
            <el-table-column label="品牌名称" align="center" prop="tmName"></el-table-column>
            <el-table-column label="品牌LOGO" align="center">
                <template #default="scope">
                    <img :src="scope.row.logoUrl" style="width: 100px;height: 50px;">
                </template>
            </el-table-column>
            <el-table-column label="品牌操作" align="center">
                <template #default="scope">
                    <el-button type="primary" size="small" icon="Edit"
                        @click="updateTradeMark(scope.row)">修改</el-button>
                    <el-popconfirm :title="`您确定要删除${scope.row.tmName}吗?`" width="200px" @confirm="deleteTradeMark(scope.row.id)">
                        <template #reference>
                            <el-button type="danger" size="small" icon="Delete">删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-pagination @current-change="getTradeMarkList" @size-change="changeSize" v-model:current-page="pageNo"
            v-model:page-size="limit" :page-sizes="[5, 10, 20, 50]" :small="false" :disabled="false" :background="true"
            layout="prev, pager, next, jumper, ->, sizes,total" :total="total" />
    </el-card>
    <!--对话框组件：在添加品牌与修改已有品牌时展示的对话框-->
    <el-dialog v-model="dialogFormVisible" :title="trademarkParams.id ? '修改品牌' : '添加品牌'">
        <el-form style="width: 80%;" :model="trademarkParams" :rules="rules" ref="formRef">
            <el-form-item label="品牌名称" label-width="100px" prop="tmName">
                <el-input placeholder="请输入品牌名称" v-model="trademarkParams.tmName"></el-input>
            </el-form-item>
            <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
                <!--upload组件属性：action图片上传路径要写/api，否则不会走代理服务器-->
                <el-upload class="avatar-uploader" action="/api/admin/product/fileUpload" :show-file-list="false"
                    :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                    <img v-if="trademarkParams.logoUrl" :src="trademarkParams.logoUrl" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="cancel">Cancel</el-button>
                <el-button type="primary" @click="confirm">
                    Confirm
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { nextTick, onMounted, reactive, ref } from 'vue';
import { reqAddOrUpdateTradeMark, reqDeleteTradeMark, reqTradeMarkList } from '@/api/product/trademark';
import type { Records, TradeMark, TradeMarkResponseData } from '@/api/product/trademark/type';
import { ElMessage, type UploadProps } from 'element-plus';

let pageNo = ref(1) //通过v-model:current-page双向绑定了
let limit = ref(5) //通过v-model:page-size双向绑定了
let total = ref(0)
let trademarkArr = ref<Records>([])
let dialogFormVisible = ref(false)
let trademarkParams = reactive<TradeMark>({
    tmName: '',
    logoUrl: ''
})
let formRef = ref()
//获取品牌列表数据接口，封装为一个函数
const getTradeMarkList = async (pager = 1) => {
    pageNo.value = pager
    let result: TradeMarkResponseData = await reqTradeMarkList(pageNo.value, limit.value);
    if (result.code === 200) {
        total.value = result.data.total
        trademarkArr.value = result.data.records
    }
}
//组件挂载完毕，获取品牌列表数据
onMounted(() => {
    getTradeMarkList();

})

function changeSize() {
    getTradeMarkList()
}
function addTradeMark() {
    dialogFormVisible.value = true
    //清空数据
    trademarkParams.id = 0
    trademarkParams.tmName = ''
    trademarkParams.logoUrl = ''

    //清空校验结果
    //第一种：ts问号语法，当formRef.value不存在时，不会报错
    // formRef.value?.clearValidate()
    //第二种：
    // if (formRef.value) {
    //     formRef.value.clearValidate()
    // }
    //第三种方法：nextTick
    nextTick(() => {
        formRef.value.clearValidate()
    })

}
function updateTradeMark(row: TradeMark) {
    //清空校验规则的错误提示信息
    nextTick(() => {
        formRef.value.clearValidate()
    })
    //对话框打开
    dialogFormVisible.value = true
    trademarkParams.id = row.id
    Object.assign(trademarkParams, row)
}
function cancel() {
    dialogFormVisible.value = false
}
async function confirm() {
    //表单校验
    await formRef.value.validate()
    let result = await reqAddOrUpdateTradeMark(trademarkParams)
    if (result.code === 200) {
        //对话框关闭
        dialogFormVisible.value = false
        //弹出提示信息
        ElMessage({
            message: trademarkParams.id ? '修改品牌成功' : '添加品牌成功',
            type: 'success',
        })
        //重新获取品牌列表数据
        //如果是新增，要查询第一页
        getTradeMarkList(trademarkParams.id ? pageNo.value : 1)
    } else {
        //添加或修改品牌失败
        ElMessage.error(result.message)
        //对话框关闭
        dialogFormVisible.value = false
    }

}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png' && rawFile.type !== 'image/gif') {
        ElMessage.error('Avatar picture must be JPG|PNG|GIF format!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('Avatar picture size can not exceed 2MB!')
        return false
    }
    return true
}

const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
    trademarkParams.logoUrl = response.data
    //图片上传成功后，清除图片校验结果
    formRef.value.clearValidate('logoUrl')
}
//表单校验规则对象
const rules = reactive({
    tmName: [
        { required: true, trigger: 'blur', validator: validateorTmName }
    ],
    logoUrl: [
        { required: true, trigger: 'change', validator: validateorLogo }
    ]
})

function validateorTmName(_rule: any, value: any, callback: any) {
    if (value.length >= 2 && value.length <= 10) {
        callback()
    } else {
        callback(new Error('品牌名称在2-10位之间'))
    }
}

function validateorLogo(_rule: any, value: any, callback: any) {
    if (value) {
        callback()
    } else {
        callback(new Error('请上传品牌图片'))
    }
}

function deleteTradeMark(id: number) {
    reqDeleteTradeMark(id).then((result) => {
        if (result.code === 200) {
            ElMessage.success('删除成功')
            //重新获取品牌列表
            getTradeMarkList(trademarkArr.value.length > 1 ? pageNo.value : pageNo.value - 1)
        } else {
            ElMessage.error(result.message)
        }
    })
}
</script>

<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>